/*
 * Copyright (c) 2022  by Junzhao
 * THIS FILE IS PART OF JAVASE Song Huongkang PROJECT
 * All Rights Reserved.
 */

package 线程通讯;


/**
 * @description 交替打印1~100
 *      wait()      使当前线程进入阻塞状态 释放同步监视器
 *      notify()    唤醒被wait的线程 有多个 优先级高 先释放
 *      notify()    唤醒所以被wait的线程
 *      必须使用在同步代码快或者同步方法中
 *      以上三个方法的调用者必须是同步代码快的同步监视器
 *      定义在Object类中！
 * @author 俊昭
 * @date 2022/4/13
*/
public class CommunicationTest {
    public static void main(String[] args) {
        Number n = new Number();
        Thread t1 = new Thread(n,"线程一");
        Thread t2 = new Thread(n,"线程二");
        t1.start();
        t2.start();
    }
}
class Number implements Runnable{
    private int number =1 ;

    @Override
    public void run() {
        while(true){
            synchronized (this) {// 选中之后alt shift t包围

                notify();// 唤醒线程

                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (number <= 100){
                    System.out.println(Thread.currentThread().getName() + number);
                    number++;

                    try {
                        wait();// 使当前线程进入阻塞状态
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }else {
                    break;
                }
            }
        }
    }
}